<?php

namespace App\Http\Controllers\Backend;

use App\Models\Role;
use App\Models\PermissionGroup;
use App\Http\Requests\Backend\RoleRequest;

class RoleController extends BaseController {

    public function index()
    {
        $roles = Role::paginate($this->pagesize);

        return view('backend.role.index')->withRoles($roles);
    }


    public function create()
    {
        $permissionGroups = PermissionGroup::all();

        return view('backend.role.create')->with('permissionGroups', $permissionGroups);
    }

    public function store(RoleRequest $request)
    {
        $redirect = $request->get('redirect');

        $role = new Role();
        $role->name         = $request->get('name');;
        $role->display_name = $request->get('display_name');
        $role->description  = $request->get('description');
        $success = $role->save();

        if($request->has('permissions')) {
            $role->perms()->sync($request->get('permissions'));
        }

        if($success) {
            return $this->responseCreatedSuccess('角色添加成功', ['redirect' => $redirect]);
        } else {
            return $this->responseCreatedFail('角色添加失败');
        }
    }

    public function show($id)
    {
        $role = Role::findOrFail($id);

        $permissionGroups = PermissionGroup::all();

        return view('backend.role.edit')->withRole($role)
                                        ->with('permissionGroups', $permissionGroups);
    }

    public function update($id, RoleRequest $request)
    {
        $redirect = $request->get('redirect');

        $role = Role::findOrFail($id);
        $role->name         = $request->get('name');;
        $role->display_name = $request->get('display_name');
        $role->description  = $request->get('description');
        $success = $role->save();

        if($request->has('permissions')) {
            $role->perms()->sync($request->get('permissions'));
        }

        if($success) {
            return $this->responseUpdatedSuccess('角色修改成功', ['redirect' => $redirect]);
        }else {
            return $this->responseUpdatedFail('角色修改失败');
        }
    }

    public function destroy($id, RoleRequest $request)
    {
        $redirect = $request->get('redirect');

        $role = Role::findOrFail($id);
        $success = $role->delete();

        if($success) {
            return $this->responseDeletedSuccess('角色删除成功', ['redirect' => $redirect]);
        }else {
            return $this->responseDeletedFail('角色删除失败');
        }
    }

}